<template>
  <div class="home">
    <UploadExcel :beforeUpload="beforeUpload" :onSuccess="handleSuccess" promptText="将云食谱文件拖拽至此处"></UploadExcel>
    <el-divider></el-divider>
    <div class="home-wrap">
      <div class="wrap-oper">
        <el-button type="primary" icon="el-icon-download" @click="exportExcel()">导出</el-button>
        <router-link to="RecipeFrom">
          <el-button type="primary" icon="el-icon-plus">新增食谱</el-button>
        </router-link>
      </div>
      <el-table :data="recipeData" border height="600" style="width: 100%" stripe>
        <el-table-column type="index" width="55" align="center" v-if="recipeData.length > 0"> </el-table-column>
        <el-table-column :prop="key" :label="value" v-for="(value, key) in recipeLable" :key="key" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            <el-image
              v-if="key === 'C'"
              style="width: 90px; height: 90px"
              :src="scope.row[key]"
              fit="contain"
              :preview-src-list="[scope.row[key]]"
            ></el-image>
            <span v-else>{{ scope.row[key] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="center" v-if="recipeData.length > 0">
          <template slot-scope="scope">
            <router-link :to="{ path: '/RecipeFrom', query: { index: scope.$index } }">
              <el-button type="text" size="small">
                编辑
              </el-button>
            </router-link>
            <el-button @click.native.prevent="delRow(scope.$index)" type="text" size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import UploadExcel from '@/components/UploadExcel.vue'

export default {
  data() {
    return {}
  },
  computed: {
    ...mapGetters('recipes', {
      recipeData: 'getRecipeData',
      recipeLable: 'getRecipeLable',
    }),
  },
  components: {
    UploadExcel,
  },
  methods: {
    beforeUpload(file) {
      const recipesName = 'recipes_deerma_deerma.mfcp.v1'
      const fileName = file.name
      if (fileName.indexOf(recipesName) === -1) {
        this.$message({
          message: `请上传云食谱文件,文件名称为:${recipesName}`,
          type: 'warning',
        })
        return false
      }
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        this.tableData = []
        return true
      }
      this.$message({
        message: '请不要上传大于1m的文件.',
        type: 'warning',
      })
      return false
    },
    handleSuccess({ results, header }) {
      console.log('handleSuccess')
      const labelMap = new Map()
      //重排数据头
      for (let i in header) {
        const sequence = String.fromCharCode(65 + parseInt(i))
        labelMap.set(sequence, header[i])
      }
      this.$store.commit(
        'recipes/setRecipeLable',
        [...labelMap.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {})
      )
      //编写数据格式
      let tableArr = []
      for (let i = 0; i < results.length; i++) {
        const tableRow = new Map()
        labelMap.forEach((value, key) => {
          tableRow.set(key, results[i][value])
        })
        tableArr.push([...tableRow.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {}))
      }
      this.$store.commit('recipes/setRecipeData', tableArr)
    },
    //删除行
    delRow(index) {
      const data = this.recipeData
      this.delIndexArr(data, index)
      //更新vuex持久化数据
      this.$store.commit('recipes/setRecipeData', data)
      const message = `移除${(index+1)}菜谱数据成功！！！`
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000,
      })
    },
    //导出数据为excel
    exportExcel() {
      console.log()
      const tHeader = new Array()
      for (let key in this.recipeLable) {
        tHeader.push(this.recipeLable[key])
      }

      const tData = new Array()
      for (let i = 0; i < this.recipeData.length; i++) {
        let rowData = new Array()
        for (let key in this.recipeData[i]) {
          rowData.push(this.recipeData[i][key])
        }
        tData.push(rowData)
      }

      const date = new Date()
      // 获取当前日期
      let nowYear = date.getFullYear()
      let nowMonth = (date.getMonth() + 1).toString().padStart(2, '0')
      let nowDate = date
        .getDate()
        .toString()
        .padStart(2, '0')
      let nowHours = date
        .getHours()
        .toString()
        .padStart(2, '0')
      const suffix = `${nowYear}${nowMonth}${nowDate}${nowHours}`
      const filename = `recipes_deerma_deerma.mfcp.v1_3_${suffix}`
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: tHeader, //表头 必填
          data: tData, //具体数据 必填
          filename: filename, //非必填
          autoWidth: false, //非必填
          bookType: 'xlsx', //非必填
        })
        this.$message({
          message: `导出${filename}文件成功!`,
          type: 'success',
        })
      })
    },
  },
}
</script>

<style scoped>
.home-wrap {
  padding: 0 30px;
}
.wrap-oper {
  overflow: hidden;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
}
</style>
